import { Node } from "cc";
import { Singleton } from "./base/Singleton";
import { createUINode } from "../utils/Util";
import { EEntity } from "../src/shared/common/Enum";
import { EPath } from "../runtime/ResManager";
import { EntityManager } from "./base/EntityManager";
/** 对象池管理 */
export class ObjectPoolManager extends Singleton {

    static get Ins() {
        return super.GetInstance<ObjectPoolManager>()
    }

    private entityPool: Map<string, Node[]> = new Map()

    /** 对象池分配对象 */
    poolAlloc(entityType: EEntity): Node {
        const pool = this.entityPool.get('' + entityType)
        if (pool && pool.length) {
            const node = pool.pop()
            node.active = true
            return node
        } else {
            return createUINode(entityType)
        }
    }

    /** 对象池添加对象 */
    poolFree(e: EntityManager) {
        const pool = this.entityPool.get('' + e.entityType)
        if (!pool) {
            this.entityPool.set('' + e.entityType, [e.node])
        } else {
            pool.push(e.node)
        }
        e.node.active = false
        e.node.setPosition(0, -800)
    }

    /** 对象池添加对象,非枚举对象类型 */
    poolFreeByStr(type: EPath, node: Node) {
        const pool = this.entityPool.get(type)
        if (!pool) {
            this.entityPool.set(type, [node])
        } else {
            pool.push(node)
        }
        node.active = false
    }

    /** 对象池分配对象 */
    poolAllocByStr(type: string): Node {
        const pool = this.entityPool.get(type)
        if (pool && pool.length) {
            const node = pool.pop()
            node.active = true
            return node
        }
        return null
    }

    /** 重置对象池 */
    reset() {
        this.entityPool = new Map()
    }

}